var express = require('express')
var app = express()
var fs = require('fs')
var path = require('path')
//引入第三方包 express-jwt
var { expressjwt } = require('express-jwt')
var jwt = require('jsonwebtoken')
//设置中间件
app.use(express.static('static')
)
// post请求参数的中间件
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

//设置token验证的中间件
app.use( expressjwt({
    secret: '1234' ,//密钥
    algorithms: ['HS256'], //算法
    //unless 设置白名单
}).unless( { path:['/user/login','/user/register'] } ) )

// 读取data.json中的数据
var filepath = path.join(__dirname, 'static/data.json')
var arr = fs.readFileSync(filepath)
arr = arr.toString() ? JSON.parse(arr) : []
// console.log(arr);
// 设置接口
// 获取数据列表
app.get('/user/list', (req, res) => {
    var { page, count } = req.query

    var newarr = arr.slice((page - 1) * count, page * count)
    // 返回的数据
    res.send({ code: 200, msg: '请求成功', list: newarr })
    // console.log(page);
    // 得到的参数
    // console.log(req.query);
})
// 登录
app.post('/user/login', (req, res) => {
    var { phone, pass } = req.body
    var i = arr.findIndex((item) => {
        return item.phone == phone && item.pass == pass
    })
    // console.log(phone);
    // console.log(req.body);
    // console.log(i);
    if (i == -1) {
        res.send({ code: 400, msg: '收到数据，登录失败' })
    } else {
        //登录成功后，生成身份令牌
        var token = jwt.sign({ phone }, "1234", { algorithm: 'HS256', expiresIn: 30 })
        res.send({ code: 200, msg: '收到数据，登录成功', name: arr[i].name, token: token })
    }
})
// 模糊查询
app.get('/user/search', (req, res) => {
    var { searchKey } = req.query
    var arr2 = arr.filter((item) => {
        return item.name.includes(searchKey)
    })
    console.log(arr2);
    res.send({ code: 200, msg: "查询成功", list: arr2 })
})
// 注册
app.post('/user/register', (req, res) => {
    var { name, phone, pass, email } = req.body
    var i = null
    console.log(phone);
    i = arr.findIndex((item) => {
        return phone == item.phone
    })
    // console.log(i);
    if (i == -1) {
        arr.push({ "email": email, "name": name, "phone": phone, "pass": pass, ingroup: "运营组", isadmin: false, status: true })
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8')
        res.send({ code: 200, msg: '注册成功' })
    }
    else {
        res.send({ code: 400, msg: '该手机号已注册，请登录!' })
    }
})
// 删除
app.post('/user/delete', (req, res) => {
    var { phone } = req.body
    console.log(phone);
    var i = arr.findIndex((item) => {
        return item.phone == phone
    })
    if (i != -1) {
        arr.splice(i, 1)
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8')
        res.send({ code: 200, msg: '删除成功', list: arr })
    }
    else {
        res.send({ code: 400, msg: '删除失败' })

    }
})
app.listen(2020, () => {
    console.log('服务器运行中');
})